package com.sphd.restaurantsystem.activitys.foods;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.adapters.GReyAdapter;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.base.RestaurantsApplication;
import com.sphd.restaurantsystem.info.GreensInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.info.SortInfo;
import com.sphd.restaurantsystem.presenter.FoodInfomationPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.utils.ImageCutUtils;
import com.sphd.restaurantsystem.view.FoodInfomationView;
import com.wzh.frame.utils.StringUtils;
import com.wzh.frame.utils.TimeUtils;
import com.wzh.frame.utils.image.LocalImageDo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class FoodInfomationActivity extends BaseActivity implements FoodInfomationView {

    private int BLANK_CODE = 0;
    @BindView(R.id.edit_imageview)
    ImageView editImageview;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.food_type_spinner)
    Spinner foodTypeSpinner;
    @BindView(R.id.food_name)
    MaterialEditText foodName;
    @BindView(R.id.food_price)
    MaterialEditText foodPrice;
    @BindView(R.id.isvipprice)
    Switch isvipprice;
    @BindView(R.id.vip_price)
    MaterialEditText vipPrice;
    @BindView(R.id.sendfood_switch)
    Switch sendfoodSwitch;
    @BindView(R.id.add_food_camera_img)
    ImageView addFoodCameraImg;
    @BindView(R.id.add_food_gallery_img)
    ImageView addFoodGalleryImg;
    @BindView(R.id.add_food_search_img)
    ImageView addFoodSearchImg;
    @BindView(R.id.food_img)
    ImageView foodImg;
    @BindView(R.id.food_update)
    Button foodUpdate;
    @BindView(R.id.content_food_infomation)
    RelativeLayout contentFoodInfomation;
    GreensInfo greensInfo;
    List<SortInfo> sortInfoList;
    Intent intent;
    Bundle bundle;
    private List<String> list;
    private ArrayAdapter<String> adapter;
    int pos = 0;
    RestaurantInfo restaurantInfo;
    private static final String TAG = "FoodInfomationActivity";
    private FoodInfomationPresenterImpl infomationPresenter;

    boolean isFinish = false;
    private List<File> fileList;//图片的集合

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_infomation);
        addActivity(this);
        ButterKnife.bind(this);
        initView();
        initEnent();
    }

    private void initEnent() {
        toolbar.setNavigationOnClickListener(view -> reTurn());
        foodTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                pos = i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        isvipprice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                changeText(b);
            }
        });

        foodPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                changeText(isvipprice.isChecked());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    private void changeText(boolean b) {
        if (!StringUtils.isEmpty(foodPrice.getText().toString())) {
            if (Double.valueOf(foodPrice.getText().toString()) > 0) {
                if (b) {
                    vipPrice.setText(turn(Double.valueOf(foodPrice.getText().toString()) * restaurantInfo.getCg_discount() / 10));
                } else {
                    vipPrice.setText(turn(foodPrice.getText().toString()));
                }
            }
        } else {
            vipPrice.setText("");
        }


    }

    private void initView() {


        intent = getIntent();
        bundle = intent.getExtras();

        BLANK_CODE = bundle.getInt(Constant.TYPE);
        pos = bundle.getInt(Constant.ITEMPOS);
        fileList = new ArrayList<>();
        sortInfoList = (List<SortInfo>) bundle.getSerializable(Constant.SORTINFOS);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        infomationPresenter = new FoodInfomationPresenterImpl(this);
        list = new ArrayList<String>();
        for (SortInfo sortInfo : sortInfoList) {
            list.add(sortInfo.getSort());
        }
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
        foodTypeSpinner.setAdapter(adapter);
        foodTypeSpinner.setSelection(pos);

        if (BLANK_CODE == 0) {
            foodTypeSpinner.setEnabled(false);
            setTitleBar(toolbar, "添加新菜");
        } else {
            greensInfo = (GreensInfo) bundle.getSerializable(Constant.GREENSINFO);
            setTitleBar(toolbar, greensInfo.getDishes_name());
            foodName.setText(greensInfo.getDishes_name());
            foodPrice.setText(turn(greensInfo.getDishes_price()));
            // TODO: 2016/11/16
            vipPrice.setText(turn(greensInfo.getDishes_vipprice()));
            //根据商品的原价*折扣率 =？返回的折扣价  如果等于则是会员价 开启状态  否则 反之···
            if (turn(greensInfo.getDishes_price() * restaurantInfo.getCg_discount() / 10, Constant.DECIMAL_POINT).
                    equals(turn(greensInfo.getDishes_vipprice(), Constant.DECIMAL_POINT))) {
                isvipprice.setChecked(true);
            } else {
                isvipprice.setChecked(false);
            }
            if (greensInfo.getDishes_isosale() == 1) {
                sendfoodSwitch.setChecked(true);
            } else {
                sendfoodSwitch.setChecked(false);
            }
        }


    }

    @OnClick({R.id.edit_imageview, R.id.food_img, R.id.add_food_search_img, R.id.food_update})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_imageview:
                break;
            case R.id.food_img:
                LocalImageDo localImageDo = new LocalImageDo(contentFoodInfomation, this);
                localImageDo.setOnClickButtonListener(new LocalImageDo.OnClickButtonListener() {
                    @Override
                    public void OnClick(View view, PopupWindow popupWindow) {
                        if (view.getId() == R.id.camara) {
//                            takePhoto();

                            ImageCutUtils.openCameraImage(FoodInfomationActivity.this);
                        } else if (view.getId() == R.id.photo) {
//                            chooseFromGallery();
                            ImageCutUtils.openLocalImage(FoodInfomationActivity.this);
                        }
                        popupWindow.dismiss();
                    }
                });
                localImageDo.showPopuWindow();
                break;
            case R.id.add_food_search_img:
                getImageList();
                break;
            case R.id.food_update:
                upDate();
                break;
        }
    }

    private void upDate() {
        if (StringUtils.isEmpty(foodName.getText().toString())) {
            toast("请输入菜品名称");
        } else {
            if (StringUtils.isEmpty(foodPrice.getText().toString())) {
                toast("请输入菜品的价格");
            } else {
                if (Double.valueOf(foodPrice.getText().toString()) <= 0) {
                    toast("请输入大于0的价格");
                } else {
                    upDateMsg();
                }
            }
        }
    }

    private void upDateMsg() {
        Map<String, String> map = new HashMap<>();
        Log.e("ISCH==", sendfoodSwitch.isChecked() + "");
        if (BLANK_CODE == 0) {
            //是否外卖
            map.put("dishOsale", sendfoodSwitch.isChecked() ? "1" : "0");
            map.put("dishVipprice", vipPrice.getText().toString());
        } else {
            map.put("dishid", greensInfo.getId() + "");
            map.put("dishVIP", turn(vipPrice.getText().toString()));
            //是否修改了分类 0为未修改 1为修改
            map.put("isUpdate", (bundle.getInt(Constant.ITEMPOS) == pos) ? "0" : "1");
            map.put("dishIsosale", sendfoodSwitch.isChecked() ? "1" : "0");
        }

        map.put("dishSortno", sortInfoList.get(pos).getSortno());
        map.put("dishName", foodName.getText().toString().trim());
        map.put("dishPrice", turn(foodPrice.getText().toString()));
        map.put("cgid", restaurantInfo.getId() + "");
        map.put("dishSortid", sortInfoList.get(pos).getId() + "");
        Log.e(TAG, map.toString());
        if (isFinish) {


            if (BLANK_CODE == 0) {
                infomationPresenter.updata(RestaurantUrl.Httptitle + RestaurantUrl.Addfood, "image", fileList, map);
            } else {
                infomationPresenter.updata(RestaurantUrl.Httptitle + RestaurantUrl.Changefoodinfo, "image", fileList, map);
            }

        } else {
            if (BLANK_CODE == 0) {
                infomationPresenter.updataNoImage(RestaurantUrl.Httptitle + RestaurantUrl.Addfood, map);
            } else {
                infomationPresenter.updataNoImage(RestaurantUrl.Httptitle + RestaurantUrl.Changefoodinfo, map);
            }
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("requestCode==", requestCode + "");
        switch (requestCode) {
            case ImageCutUtils.GET_IMAGE_BY_CAMERA:
                //拍照
                ImageCutUtils.cropImageData(FoodInfomationActivity.this, ImageCutUtils.imageUriFromCamera);
                break;
            case ImageCutUtils.GET_IMAGE_FROM_PHONE:
                //读取图库
                if (data != null && data.getData() != null) {
                    // 对图片进行裁剪
                    Uri a = data.getData();
                    ImageCutUtils.cropImageData(this, a);
                    // imageUriFrom(a);
                }
                break;
            case ImageCutUtils.CROP_IMAGE:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap photo = extras.getParcelable("data");
                        foodImg.setImageBitmap(photo);//mHeadImg是个Imageview
                        isFinish = true;
                        File file = ImageCutUtils.saveBitmap(photo, context);
                        if (file != null) {
                            fileList.clear();
                            fileList.add(file);
                        } else {
                            return;
                        }
                    } else {
                        return;
                    }

                } else {
                    return;
                }
                break;
        }


    }

    private void getImageList() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                "https://route.showapi.com/95-106?",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("S==", response);
                        showImageDialog(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                toast("获取失败");
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("showapi_appid", "19203");
                map.put("showapi_sign", "b62743c6d4bc4c0e9784a32b48bcf955");
                map.put("name", foodName.getText().toString());
                map.put("showapi_timestamp", TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_NO_TRIM));
                return map;
            }
        };
        stringRequest.setTag("girltype");

        RestaurantsApplication.getRequestQueue().add(stringRequest);


    }

    private void showImageDialog(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response).getJSONObject("showapi_res_body");
            Log.e("OB====", jsonObject.getString("msg"));
            if (!StringUtils.isEmpty(jsonObject.getString("msg"))) {
                toast(jsonObject.getString("msg"));
                return;
            }
            List<String> stringList = getStringImg(new JSONObject(response).getString("showapi_res_body"));
            if (stringList.size() != 0) {
                Dialog fiexoDialog = new Dialog(context);
                View view = View.inflate(context, R.layout.swf_and_recy, null);
                fiexoDialog.setTitle(foodName.getText().toString());
                fiexoDialog.setContentView(view);
                RecyclerView diaRecy = $(R.id.my_recy, view);
                setGRecy(diaRecy, 2);
                GReyAdapter gReyAdapter = new GReyAdapter(R.layout.item_image, stringList);
                diaRecy.setAdapter(gReyAdapter);
                fiexoDialog.show();
                diaRecy.addOnItemTouchListener(new OnItemClickListener() {
                    @Override
                    public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                        fiexoDialog.dismiss();
                        //选择图片
                        downImage((String) baseQuickAdapter.getItem(i));
                    }
                });
            } else {
                toast("未能查找到相关图片");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void downImage(String url) {
        ImageRequest imageRequest = new ImageRequest(
                url,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        ImageCutUtils.cropImageData(FoodInfomationActivity.this, ImageCutUtils.getUriFromBitmap(context, response));
                    }
                }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RestaurantsApplication.getRequestQueue().add(imageRequest);
    }


    private List<String> getStringImg(String string) throws JSONException {
        List<String> list = new ArrayList<String>();
        JSONArray jsonArray = new JSONArray(new JSONObject(string).getString("cbList"));
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (jsonObject.has("imgList")) {
                JSONArray foodJsaonArray = jsonObject.getJSONArray("imgList");
                for (int j = 0; j < foodJsaonArray.length(); j++) {
                    if (foodJsaonArray.getJSONObject(j).has("imgUrl")) {
                        list.add(foodJsaonArray.getJSONObject(j).getString("imgUrl"));
                    }
                }
            }
        }
        return list;
    }

    @Override
    public void recSussed() {
        //是否修改了分类 0为未修改 1为修改

        if (BLANK_CODE == 0) {
            isAgainAddFood();
        } else {
            toast("成功");
            reTurn();
        }
    }

    private void reTurn() {
        setResult(1);
        finishActivity(this);
    }

    //是否再次添加食物
    private void isAgainAddFood() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);
        alertDialogBuilder
                .setIcon(R.mipmap.ic_launcher_small)
                .setTitle("提示")
                .setMessage("已经上传成功是否再次添加菜品?")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                clearImput();
                            }
                        })
                .setNegativeButton("返回",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                reTurn();
                            }
                        });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }

    private void clearImput() {
        foodName.setText("");
        foodPrice.setText("");
        isvipprice.setChecked(false);
        sendfoodSwitch.setChecked(false);
        isFinish = false;

    }


    @Override
    public void recError() {
        toast("修改失败，请重试。");
    }


    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
